package org.wattdepot.cli;

import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClientException;
import org.wattdepot.resource.sensordata.jaxb.SensorData;

/**
 * Executes the sensordata command.
 * 
 * @author Scott Wong and Kelli Sawai
 * 
 */
public class SensorInfo extends CommandLineInterface implements WattDepotCliCommand {

  /**
   * Executes and returns the results of the sensordata command.
   * 
   * @param args The arguments required to execute this method.
   * @return The results of the command.
   */
  public String doCommand(String args) {
    try {
      if (args.matches("sensordata \\w* timestamp \\S*")) {
        String[] sensorInput = args.split(" ");
        String sourceName = sensorInput[1];
        String timestamp = sensorInput[3];   
        XMLGregorianCalendar gTimestamp = toTimestamp(timestamp);
        
        // Check if the timestamp is in the future.
        XMLGregorianCalendar now =
            DatatypeFactory.newInstance()
                .newXMLGregorianCalendar(new GregorianCalendar());
        if (gTimestamp.compare(now) >= 0) {
          return futureTimestampMessage;
        }
        
        return listSensorDataTimestamp(sourceName, gTimestamp);
      }
      else {
        return "The command you have entered is invalid.";
      }
    }
    catch (WattDepotClientException e) {
      return "An error occured while executing the requested command.";
    }
    catch (Exception e) {
      return "An error occured while executing the requested command.";
    }
  }

  /**
   * Prints information about a single sensor data instance.
   * 
   * @param source The name of the power plant.
   * @param timestamp The date requested.
   * @return The sensor data for the selected timestamp.
   * @throws WattDepotClientException If problems occur obtaining the list of sources.
   */
  private String listSensorDataTimestamp(String source, XMLGregorianCalendar timestamp)
      throws WattDepotClientException {
    StringBuffer buffer = new StringBuffer(50);

    try {
      SensorData data = client.getSensorData(source, timestamp);
      String dataSource = data.getSource();

      buffer.append("Tool: ").append(data.getTool()).append(nl);
      buffer.append("Source: ").append(dataSource.substring(51)).append(nl);
      buffer.append("Properties: ").append(formatProperties(data.getProperties()));

      return buffer.toString();
    }
    catch (ResourceNotFoundException e) {
      return resourceMessage;
    }
    catch (BadXmlException e) {
      return badXmlMessage;
    }
    catch (NotAuthorizedException e) {
      return notAuthorizedMessage;
    }
  }
}
